package com.webserver.core;

import com.webserver.http.HttpRequest;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 处理与指定客户端的一次HTTP交互
 * 完成一次交互由三步构成：
 * 1：解析请求
 * 2：处理请求
 * 3：响应客户端
 *
 */
public class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            //1解析请求
            HttpRequest request = new HttpRequest(socket);

            //2处理请求
            String path = request.getUri();
            File file = new File("./webapps"+path);

            int statusCode = 200;
            String statusReason = "OK";

            if (file.exists() && file.isFile()) {

            }else {
                statusCode = 404;
                statusReason = "Not Found";
                file = new File("./webapps/root/404.html");
            }


            //3发送响应
        /*  HTTP/1.1 200 OK(CRLF)
            Content-Type: text/html(CRLF)
            Content-Length: 2546(CRLF)(CRLF)
            1011101010101010101......
         */
            OutputStream out = socket.getOutputStream();
            //3.1：发送状态行
            //判断地址是否存在文件资源


                String line = "HTTP/1.1"+" "+statusCode+" "+statusReason;
                byte[] data = line.getBytes("ISO8859-1");
                out.write(data);
                out.write(13);
                out.write(10);

                //3.2:发送响应头
                line = "Content-Type: text/html";
                data = line.getBytes("ISO8859-1");
                out.write(data);
                out.write(13);
                out.write(10);

                line = "Content-Length: " + file.length();
                data = line.getBytes("ISO8859-1");
                out.write(data);
                out.write(13);
                out.write(10);

                out.write(13);
                out.write(10);

                //3.3:发送响应正文
                FileInputStream fis = new FileInputStream(file);
                data = new byte[1024 * 10];
                int len;
                while ((len = fis.read(data)) != -1) {
                    out.write(data, 0, len);
                }
                System.out.println("发送相应完毕！");





        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //一次HTTP交互完毕后要与客户端断开连接(Http协议要求)
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
